//
//  HMSearchController.m
//  HMMarket
//
//  Created by 孙鹏飞 on 2017/5/10.
//  Copyright © 2017年 homai. All rights reserved.
//

#import "HMSearchController.h"
#import "SearchModel.h"
#import "HMProductDetailViewController.h"


@interface HMSearchController () <UITextFieldDelegate, UICollectionViewDelegate,UICollectionViewDataSource, UICollectionViewDelegateFlowLayout, UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) UITextField * searchTF;
@property (nonatomic, strong) UITableView * tableView;
@property (nonatomic, strong) UICollectionView * collectionView;

@property (nonatomic, copy) NSString * keyWord;
@property (nonatomic, strong) NSArray * searchArray;
@property (nonatomic, strong) NSMutableArray * resultArray;
@property (nonatomic, strong) UIImageView * nodata;

@end

@implementation HMSearchController

- (NSArray *)searchArray
{
    if (!_searchArray) {
        _searchArray = [NSMutableArray array];
    }
    return _searchArray;
}

- (NSMutableArray *)resultArr
{
    if (!_resultArray) {
        _resultArray = [NSMutableArray array];
    }
    return _resultArray;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = kBackGolor;
    [self setupNav];
    [self setupSearchView];
}

- (void)setupNav
{
    self.BackBarItem.hidden = YES;
    [self.RightBarItem setTitle:@"取消" forState:UIControlStateNormal];
    [self.RightBarItem addTarget:self action:@selector(cancle) forControlEvents:UIControlEventTouchUpInside];
    
    UITextField * searchTF = [[UITextField alloc] initWithFrame:CGRectMake(20, 25, KWidthSCREEN - 90, 32)];
    searchTF.delegate = self;
    [self.CustomNaviBar addSubview:searchTF];
//    [searchTF becomeFirstResponder];
    self.searchTF = searchTF;
    
    searchTF.placeholder = @"请输入搜索内容";
    searchTF.font = [UIFont systemFontOfSize:15];
    searchTF.textColor = kTextColor;
    searchTF.backgroundColor = [UIColor whiteColor];
    searchTF.clearButtonMode = UITextFieldViewModeAlways;
    searchTF.layer.cornerRadius = 16;
    searchTF.layer.masksToBounds = YES;
    
    UIImageView * leftView = [[UIImageView alloc] init];
    leftView.contentMode = UIViewContentModeScaleAspectFit;
    leftView.bounds = CGRectMake(13, 0, 30, 15);
    leftView.image = [UIImage imageNamed:@"btn_seek"];
    
    searchTF.leftView = leftView;
    searchTF.leftViewMode = UITextFieldViewModeAlways;
    searchTF.returnKeyType = UIReturnKeySearch;
    
    // 使用通知来监听输入框内容的变化
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(textFieldChangeWords) name:@"UITextFieldTextDidChangeNotification" object:nil];
}

- (void)setupSearchView
{
    // 搜索结果列表
    UICollectionViewFlowLayout * flowLayout = [[UICollectionViewFlowLayout alloc] init];
    [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
    
    UICollectionView * collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 64) collectionViewLayout:flowLayout];
    self.collectionView = collectionView;

    collectionView.backgroundColor = [UIColor groupTableViewBackgroundColor];
    collectionView.delegate = self;
    collectionView.dataSource = self;
    collectionView.showsVerticalScrollIndicator = NO;
    
    [self.collectionView registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"collection"];
    [self.view addSubview:collectionView];
    
    // 搜索历史列表
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, KWidthSCREEN, KHeightSCREEN - 64) style:UITableViewStyleGrouped];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.showsVerticalScrollIndicator = NO;
    self.tableView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:self.tableView];
    
    NSArray * searchArray = [HMUser objectForKey:@"LocalSearch"];
    self.searchArray = searchArray;
    [self.tableView reloadData];

    _nodata =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"default_search"]];
    _nodata.centerX =KWidthSCREEN/2;
    _nodata.centerY =(KHeightSCREEN - 150)/2;
    [self.collectionView addSubview:_nodata];
}

- (void)textFieldChangeWords
{
    if (self.searchTF.isFirstResponder) {
        UITextRange * range = [self.searchTF markedTextRange];
        if (range == nil) {
            NSString * textStr = self.searchTF.text;
            [self searchDataWithKeyword:textStr];
        }
    }
}

- (void)searchDataWithKeyword:(NSString *)keyWord
{
    self.keyWord = keyWord;
    MyLog(@"%@",keyWord);
    
    if (keyWord.length == 0 || [keyWord isEqualToString:@""]) {
        self.tableView.hidden = NO;
        self.collectionView.hidden = YES;
        [self.tableView reloadData];
        [self.collectionView reloadData];
        [self.resultArray removeAllObjects];
        return;
    }
    [self.resultArray removeAllObjects];
    // 请求搜索数据
    [self getDataWithKeyword:keyWord];
}

- (void)getDataWithKeyword:(NSString *)keyWord
{
    // 点击屏幕搜索框失去焦点
    [self.searchTF resignFirstResponder];
    
    
    NSDictionary *param =@{@"searchname":keyWord};
    [HttpBaseTool get:kSearchUrl params:param success:^(id responseObj) {
        self.resultArray =[SearchModel mj_objectArrayWithKeyValuesArray:responseObj[@"data"]];
//        [self.modelArr addObjectsFromArray:modelArr];
        if (_resultArray.count>0) {
            self.tableView.hidden = YES;
            self.collectionView.hidden = NO;
            [self.tableView reloadData];
            [self.collectionView reloadData];
            _nodata.hidden =YES;
           
            NSArray * searchArr = [HMUser objectForKey:@"LocalSearch"];
            NSMutableArray * tempArr = [NSMutableArray array];
            [tempArr addObjectsFromArray:searchArr];
            
            for (NSString * key in tempArr) {
                if ([key isEqualToString:keyWord]) {
                    return;
                }
            }
            
            [tempArr insertObject:keyWord atIndex:0];
            [HMUser setObject:tempArr forKey:@"LocalSearch"];
            [HMUser synchronize];
            self.searchArray = tempArr;

        }else{
            if (keyWord.length !=0) {
                self.tableView.hidden = YES;
                self.collectionView.hidden = NO;
            }
            _nodata.hidden =NO;
        }
        [self.collectionView reloadData];
    } failure:^(NSError *error) {
        [HMHUDManager showHUDWithText:NetWorkError];
    }];
    
    }

#pragma mark - textField代理
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    NSString * textStr = self.searchTF.text;
    [self searchDataWithKeyword:textStr];
    return YES;
}

- (BOOL)textFieldShouldClear:(UITextField *)textField
{
    textField.text = @"";
    [self searchDataWithKeyword:textField.text];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    // 点击屏幕搜索框失去焦点
    [self.searchTF resignFirstResponder];
}

#pragma mark - tableView代理
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.searchArray.count >= 8) {
        return 8;
    }
    return self.searchArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 44;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellID = @"table";
    UITableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
    }
    cell.separatorInset = UIEdgeInsetsZero;
    cell.textLabel.text = self.searchArray[indexPath.row];
    cell.textLabel.textColor = kTipTextColor;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString * keyword = self.searchArray[indexPath.row];
    self.searchTF.text = keyword;
    [self getDataWithKeyword:keyword];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 200;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 40;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    return @"搜索历史";
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section
{
    UIView * bgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KWidthSCREEN, 200)];
    bgView.backgroundColor = [UIColor whiteColor];
    
    UIButton * cleanBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    cleanBtn.frame = CGRectMake(0, 0, 120, 30);
    cleanBtn.centerX = bgView.centerX;
    cleanBtn.centerY = 100 - 15;
    cleanBtn.layer.cornerRadius = 5;
    cleanBtn.layer.borderColor = kMainColor.CGColor;
    cleanBtn.layer.borderWidth = 0.5;
    [cleanBtn setTitle:@"清空历史搜索" forState:UIControlStateNormal];
    [cleanBtn setTitleColor:kMainColor forState:UIControlStateNormal];
    cleanBtn.backgroundColor = [UIColor whiteColor];
    cleanBtn.titleLabel.font = [UIFont boldSystemFontOfSize:12];
    cleanBtn.titleLabel.textAlignment = NSTextAlignmentCenter;
    [cleanBtn addTarget:self action:@selector(cleanAction) forControlEvents:UIControlEventTouchUpInside];
    [bgView addSubview:cleanBtn];
    
    return bgView;
}

- (void)cleanAction
{
    [HMUser removeObjectForKey:@"LocalSearch"];
    [HMUser synchronize];
    self.searchArray =@[];
    [self.tableView reloadData];
}

#pragma mark - collectionView代理
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.resultArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString * cellID = @"collection";
    UICollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    cell.backgroundColor = [UIColor whiteColor];
    
    SearchModel * model = self.resultArray[indexPath.item];
    
    // 添加icon
    UIImageView * iconView = [[UIImageView alloc] initWithFrame:CGRectMake(7, 7,(KWidthSCREEN -2)/3 - 14, (KWidthSCREEN -2)/3 - 14)];
    [iconView sd_setImageWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",kImageUrl,model.logo]] placeholderImage:[UIImage imageNamed:@"ProductList_PlaceHolder"]];
    [cell.contentView addSubview:iconView];
    
    // 添加特价图标
    UIImageView * specialView = [[UIImageView alloc] initWithFrame:CGRectMake((KWidthSCREEN -2)/3 - 28, 0, 28, 22)];
    specialView.image = [UIImage imageNamed:@"ProductList_saleprice"];
    [cell.contentView addSubview:specialView];
    
    if ([model.is_hot isEqualToString:@"特价菜品"]) {
        specialView.hidden = NO;
    } else {
        specialView.hidden = YES;
    }
    
    // 添加标题
    UILabel * title = [[UILabel alloc] initWithFrame:CGRectMake(10, (KWidthSCREEN -2)/3, KWidthSCREEN/3 - 21, 32)];
    title.numberOfLines = 2;
    title.textAlignment = NSTextAlignmentLeft;
    title.font = [UIFont systemFontOfSize:13];
    title.textColor = [UIColor blackColor];
    title.text = model.item_name;
    [cell.contentView addSubview:title];
    
    // 价格
    UILabel * des = [[UILabel alloc] initWithFrame:CGRectMake(10, (KWidthSCREEN -2)/3 + 30, KWidthSCREEN/3 - 21, 20)];
    des.textAlignment = NSTextAlignmentLeft;
    des.font = [UIFont systemFontOfSize:13];
    des.textColor = [UIColor redColor];
    des.text = [NSString stringWithFormat:@"¥%@/%@",model.item_price,model.weight];
    [cell.contentView addSubview:des];
    
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    SearchModel * model = self.resultArray[indexPath.item];
    HMProductDetailViewController *vc = [[HMProductDetailViewController alloc] init];
    vc.pro_id = model.id;
    vc.NavigationBarHidden= NO;
    [self.navigationController pushViewController:vc animated:YES];
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    return (CGSize){(KWidthSCREEN - 2)/3,(KWidthSCREEN - 2)/3 + 55};
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    return (CGSize){KWidthSCREEN,0};
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section
{
    return UIEdgeInsetsMake(0, 0, 0, 0);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section
{
    return 1;
}

- (void)cancle
{
    [self.navigationController popViewControllerAnimated:YES];
    MyLog(@"cancle");
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
